#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from xpy3lib.LoggableObject import LoggableObject


class XRetryableSave(LoggableObject):
    db_conn = None
    table_name = None
    schema = None
    dataframe = None
    max_times = -1

    def __init__(self, p_db_conn=None, p_table_name=None, p_schema=None, p_dataframe=None, p_max_times=1):
        super(XRetryableSave, self).__init__()
        self.db_conn = p_db_conn
        self.table_name = p_table_name
        self.schema = p_schema
        self.dataframe = p_dataframe
        self.max_times = p_max_times
        self.__times = -1

    def redo(self):
        try:
            self.__times += 1
            if self.__times < self.max_times:
                self.dataframe.to_sql(name=self.table_name.lower(),
                                      con=self.db_conn,
                                      schema=self.schema.lower(),
                                      index=False,
                                      if_exists='append',
                                      chunksize=1000)
        except Exception as e:
            self.logger.error(str(e))
            self.redo()
